package com.dingzhen.utils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class JacksonUtils {
    private static ObjectMapper objectMapper = new CustomerObjectMapper();

    public JacksonUtils() {
    }

    public static <T> Map<String, T> toMap(String jsonStr, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        jsonStr = jsonStr.trim();
        TypeReference<Map<String, T>> typeRef = new TypeReference<Map<String, T>>() {
        };
        return !jsonStr.startsWith("[") ? (Map)objectMapper.readValue(jsonStr, typeRef) : null;
    }

    public static <T> LinkedHashMap<String, T> toLinkedHashMap(String jsonStr, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        jsonStr = jsonStr.trim();
        TypeReference<LinkedHashMap<String, T>> typeRef = new TypeReference<LinkedHashMap<String, T>>() {
        };
        return !jsonStr.startsWith("[") ? (LinkedHashMap)objectMapper.readValue(jsonStr, typeRef) : null;
    }

    public static <T> T toObject(String jsonStr, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        if (jsonStr == null) {
            return null;
        } else {
            jsonStr = jsonStr.trim();
            return objectMapper.readValue(jsonStr, clazz);
        }
    }

    public static <T> List<T> toList(String jsonStr, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        jsonStr = jsonStr.trim();
        TypeReference<List<T>> typeRef = new TypeReference<List<T>>() {
        };
        return jsonStr.startsWith("[") ? (List)objectMapper.readValue(jsonStr, typeRef) : null;
    }

    /** @deprecated */
    @Deprecated
    public static String ObjectToString(Object obj) {
        return objectToString(obj);
    }

    public static String objectToString(Object obj) {
        if (obj == null) {
            return "null";
        } else if (obj instanceof String) {
            return obj.toString();
        } else {
            try {
                return objectMapper.writeValueAsString(obj);
            } catch (JsonProcessingException var2) {
                var2.printStackTrace();
                return "null";
            }
        }
    }
}
